<#assign ctx=request.contextPath />
<#import '${ctx}/sys/include/head.html' as d />
<#import '${ctx}/sys/include/body.html' as c />
<#import '${ctx}/sys/include/table/select.html' as select />
<!DOCTYPE html>
<html>
<head>
    <@d.head title="pie" />
    <!--<script src="${ctx}/resource/echart/echarts.js/" type="text/javascript"></script>-->
    <!--<script src="${ctx}/resource/echart/theme/macarons.js"></script>-->

    <script src="${ctx}/resource/antv/g2.js"></script>
    <script src="${ctx}/resource/antv/dataset.js"></script>
    <style>::-webkit-scrollbar {
        display: none;
    }

    html, body {
        overflow: hidden;
        height: 100%;
        margin: 0;
    }</style>
</head>
<@c.body>
<div class="layui-tab layui-tab-brief" lay-filter="graph_config">
    <ul class="layui-tab-title layui-row">
        <li class="layui-col-md1">图表展示</li>
        <li class="layui-col-md1 layui-this">图表设置</li>
        <button id="save_table" class="layui-col-md1 layui-col-md-offset9 layui-btn layui-btn-sm">
            保存图表
        </button>
    </ul>
    <div class="layui-tab-content">
        <div class="layui-tab-item">
            <div class="layui-form">
                <div id="condition_span">
                    <div class="layui-btn-group" id="remove_filter">
                        <button class="layui-btn layui-btn-sm layui-btn-primary ">
                            <i class="layui-icon">&#x1006;</i>删除过滤规则
                            <!--执行删除操作-->
                        </button>
                    </div>
                    <div class="layui-btn-group" id="add_filter">
                        <button class="layui-btn layui-btn-sm layui-btn-primary ">
                            <i class="layui-icon">&#xe654;</i>添加过滤规则
                            <!--弹出选择框-->
                        </button>
                    </div>
                </div>
            </div>
            <div id="pie" class="text-center"></div>
        </div>
        <div class="layui-tab-item layui-show">
            <div class="layui-container" style="margin-top: 12px;">
                <div class="layui-row">
                    <form class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">选择数据源</label>
                            <div class="layui-input-block"><@select.table name="dsId"
                                show="dsName" url="${ctx}/biz/c/p/ds-select-table" />
                            </div>
                        </div>
                        <label>指标设置</label>
                        <hr/>
                        <div class="layui-card">
                            <div class="layui-card-header">分析指标</div>
                            <div class="layui-card-body">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">计算方式</label>
                                    <div class="layui-input-block">
                                        <select name="aggregation" lay-verify="required"
                                                lay-filter="metrics_select">
                                            <option value="count">总数</option>
                                            <option value="sum">累和</option>
                                            <option value="avg">平均值</option>
                                            <option value="unique">唯一值</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-form-item layui-hide">
                                    <label class="layui-form-label">计算字段</label>
                                    <div class="layui-input-block"><@select.table
                                        name="metrics" show="metricsName"
                                        url="${ctx}/biz/c/p/field-select-table" />
                                    </div>
                                </div>
                            </div>
                        </div>

                        <label>维度设置</label>
                        <hr/>
                        <div class="layui-form-item">
                            <label class="layui-form-label">拆分方式</label>
                            <div class="layui-input-block">
                                <select name="aggregation" lay-verify="required"
                                        lay-filter="aggs_select">
                                    <option value="term">按字段值</option>
                                    <option value="date">按时间</option>
                                    <option value="range">按区间</option>
                                    <option value="filter">按条件</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">聚合字段</label>
                            <div class="layui-input-block"><@select.table name="aggs"
                                show="aggsName" url="${ctx}/biz/c/p/field-select-table" />
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</@c.body>
<script type="text/javascript">
    layui.use(['form', 'element', 'appJs', 'layer'], function () {
        var $ = layui.$;
        var form = layui.form, element = layui.element, app = layui.appJs, layer = layui.layer;

        var redraw = true;

        element.on('tab(graph_config)', function (data) {
            console.log(data.index); //得到当前Tab的所在下标
            if (data.index == 0) {
                if (redraw)
                    draw();
            }
        });

        form.on('select(metrics_select)', function (data) {
            var ele = data.elem;
            var val = data.value;
            console.log("=>" + val)
            if (val != 'count') {
                $(ele).parent().parent().next().removeClass('layui-hide');
            } else {
                $(ele).parent().parent().next().addClass('layui-hide');
            }
        });
        form.render();
        var chart;

        function draw() {
            var data = [{
                item: 'SN',
                count: 2992163,
            }, {
                item: 'TTFF',
                count: 2409815,
            }, {
                item: 'CIT',
                count: 2398765,
            }, {
                item: 'LTEBT',
                count: 1782364,
            }, {
                item: 'SMTCheck',
                count: 1733841,
            }, {
                item: 'WBG',
                count: 674218,
            }
            ];
            if (typeof chart != 'undefined') {
                chart.clear();
            }
            chart = new G2.Chart({
                container: 'pie',
                forceFit: true,
                height: window.innerHeight
            });

            var op = {
                data: data,
                transform: {
                    type: 'percent',
                    field: 'count',
                    dimension: 'item',
                    as: 'percent'
                },
                scale: {
                    field: 'percent',
                    conf: {
                        percent: {
                            formatter: function formatter(val) {
                                val = (val * 100).toFixed(2) + '%';
                                return val;
                            }
                        }
                    }
                },
                legend: false,
                coord: {
                    name: 'theta',
                    conf: {
                        radius: 0.5
                    }
                },
                tooltip: {
                    showTitle: false
                },
                position: 'percent',
                color: 'item',
                event: [{
                    name: 'interval:click',
                    func: function (ev) {
                        console.log('--->' + ev.data._origin.item);
                    }
                }],
                geom: {
                    tooltip: {
                        name: 'item*percent',
                        func: function (item, percent) {
                            percent = (percent * 100).toFixed(2) + '%';
                            return {
                                name: item,
                                value: percent
                            };
                        }
                    },
                    select: false,
                    style: {
                        lineWidth: 1,
                        stroke: '#fff'
                    }
                }
            }

            app.pie(chart, op);
            chart.render();
            redraw = false;
        }

        //save_table info
        $("#save_table").unbind('click');
        $("#save_table").bind('click', function () {
            layer.prompt({title: '保存图表-请输入名称'}, function (value, index) {
                layer.close(index);
                saveChart(value);
            });
        });

        function saveChart(chartName) {
            // var req = buildRequest();
            var chartSettingData = {
                chartName: chartName,
                // chart_req: req,
                chartReq: "待完成2",
                chartFilters: "待完成3",
                chartCustom: "待完成4"
            };
            app.ajax('post', '${ctx}/biz/chart/chart_setting/add', chartSettingData, function (data) {
                if (data.code == 0) {
                    layer.msg(data.msg);
                } else {
                    layer.msg(data.code + ": " + data.msg);
                }
            });
        }

        function removeFilter() {
        }

        function addFilter() {
        }

        function buildRequest() {
            aggregationsArray.length = 0;
            metricsArray.length = 0;
            var $metricCards = $('div[name="metric_card"]');
            var $aggregationCard = $('div[name="aggregation_card"]')
            var metrics = [];
            $metricCards.each(function (id, card) {
                var metricObj = {};
                var metric_type = $(card).find('input[name="metric_type"]').val();
                var metric_field = $(card).find('input[name="metrics"]').val();
                if (metric_type == '_count') {
                    metrics.push('count()');
                    metricsArray.push({aggs: '_count'})
                } else {
                    if (typeof metric_type != 'undefined' && typeof metric_field != 'undefined')
                        metrics.push(metric_type + '(' + metric_field + ')');
                    app.async_ajax('get', '${ctx}/biz/data/ds/field/get', {id: metric_field}, function (d) {
                        if (d.code == 0) {
                            var field = d.values.data;
                            field.aggs = metric_type;
                            metricsArray.push(field);
                        }
                    });
                }
            });
            $aggregationCard.each(function (id, card) {
                var aggregation_type = $(card).find('input[name="aggregation_type"]').val();
                var aggregation_field = $(card).find('input[name="aggs"]').val();
                if (typeof aggregation_type != 'undefined' && typeof aggregation_field != 'undefined') {
                    app.async_ajax('get', '${ctx}/biz/data/ds/field/get', {id: aggregation_field}, function (d) {
                        if (d.code == 0) {
                            var field = d.values.data;
                            aggregationsArray.push({type: aggregation_type, field: field});
                        }
                    });
                }
            });
            var metrics_request = metrics.join(',');
            console.log(metrics_request);
            target_dimension = aggregationsArray[0].field;
            var dimension = aggregationsArray[0].type + '(' + aggregationsArray[0].field.id + ')';
            var req = {
                metrics: metrics_request,
                ds_id: $('input[name="dsId"]').val(),
                dimension: dimension
            };
            return req;
        }
    });
</script>